/*
 * jQuery UI Feeds v0.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://mjonrails.blogspot.com/
 *
 * Depends:
 *   javascript.extensions.js
 */
(function($){
	$.fn.extend({		
		drawPoint:function(x,y){
			if (!this._validateCoords(x, y)){
				return this;
			}
			var dot = this._dotTemplate.format(x,y);
			$(this).append(dot);
			return this;
		},
		
		drawLine: function(fromX, fromY, toX, toY){
			// only posite x and y coords are valid
			if (!this._validateCoords(fromX, fromY)){
				return this;
			}
			if (!this._validateCoords(toX, toY)){
				return this;
			}
			// linear function is y=k*x + n
			var k = (toY - fromY)/(toX - fromX);
			var n = fromY  - k * fromX;
			
			// needed for lines that has  |k| > 1 or you will got dots in line
			var stepMultiplier = 1; 
			if ( isFinite(k) && Math.abs(k) > 1  ){
				stepMultiplier = Math.round(k);
			}
			
			// for finite |k| 
			if (isFinite(k)){
				var startFrom = (fromX < toX)? fromX: toX ;
				var endTo = (fromX > toX)? fromX: toX ;
				for(var x = startFrom * stepMultiplier; x <= endTo * stepMultiplier; x++){
					var	y = k * x/stepMultiplier + n;				
					this.drawPoint(x/stepMultiplier  ,y);
				}				
			}else{
				// for infinite |k| x is calculated not y
				var startFrom = (fromY < toY)? fromY: toY ;
				for(var y = 0; y <= Math.abs(fromY - toY); y++){
					this.drawPoint(fromX , y + startFrom );
				}	
			}
			
			return this;
		},
		
		drawArc : function (centerX,centerY, radius, fromAngle, toAngle) {
			if (!this._validateCoords(centerX, centerY)){
				return this;
			}
			for ( var angle = fromAngle * radius; angle <=  toAngle * radius; angle++){
				var x = Math.cos(angle/radius) * radius;
				var y = Math.sin(angle/radius) * radius;
				
				x = x  + centerX ;
				y = y  + centerY ;
				
				this.drawPoint(x,y);
			}	
			return this;
		},
		
		drawCircle : function(centerX,centerY, radius) {
			return this.drawArc(centerX, centerY, radius, 0, 2*Math.PI);					
		},
		
		
		/* private */
		_dotTemplate : "<div class=\"dot\" style=\"left:{0}px;top:{1}px;\">&nbsp;</div>",
		_validateCoords: function(x,y){
			if (x < 0 || y < 0) {
				alert("Negative coordinares are not supported!");
				return false;
			}
			return true;
		}
	});
})(jQuery);